package v1

import (
	"github.com/dchest/captcha"
	"github.com/gin-gonic/gin"
	"github.com/hashicorp/go-uuid"
	"github.com/mssola/user_agent"
	"net/http"
	"os"
	"perfect-admin/global/response"
	"perfect-admin/middleware"
	"perfect-admin/model"
	"perfect-admin/model/request"
	"perfect-admin/service"
	"perfect-admin/utils"
	"time"
)

func Login(c *gin.Context){
	var loginForm request.LoginForm
	if err := c.ShouldBindJSON(&loginForm); err != nil {
		c.JSON(201, gin.H{"msg": "参数接收错误", "data": nil})
		service.InsertLoginLog(c, "数据解析错误", "1", loginForm.Username)
		return
	}
	var msg, status string
	if captcha.VerifyString(loginForm.CaptchaId, loginForm.Captcha) {
		user, msg, isPass := service.LoginCheck(loginForm.Username,loginForm.Password)
		if !isPass {
			status = "1"
			c.JSON(202, gin.H{
				"msg":msg,
				"data":nil,
			})
		}else {
			token, msg, ok := middleware.GenerateToken(c, user)
			if !ok {
				status = "1"
				c.JSON(203, gin.H{"msg": msg, "data": nil})
			}else {
				status = "0"
				c.JSON(http.StatusOK, gin.H{"msg":msg, "token": token, "data": user})
			}
		}
		service.InsertLoginLog(c, msg, status, loginForm.Username)
	}else {
		msg = "验证码错误"
		status = "1"
		c.JSON(210, gin.H{"msg": msg, "data": nil})
		service.InsertLoginLog(c, msg, status, loginForm.Username)
	}
	return
}

func LogOut(c *gin.Context) {
	var loginlog model.SysLoginLog
	ua := user_agent.New(c.Request.UserAgent())
	loginlog.Ipaddr = c.ClientIP()
	location := utils.GetLocation(c.ClientIP())
	loginlog.LoginLocation = location
	loginlog.LoginTime = time.Now()
	loginlog.Status = "0"
	loginlog.Remark = c.Request.UserAgent()
	browserName, browserVersion := ua.Browser()
	loginlog.Browser = browserName + " " + browserVersion
	loginlog.Os = ua.OS()
	loginlog.Platform = ua.Platform()
	loginlog.Username = utils.GetClaims(c).Username
	loginlog.Msg = "退出成功"
	service.AddOneLoginLog(loginlog)
	response.ResponseSuccess(c,  "退出成功")
}

func UploadImage(c *gin.Context) {
	image_file, err := c.FormFile("image")
	if err != nil {
		c.JSON(203, gin.H{"msg": err, "img_path": nil})
		return
	}
	uid, _ := uuid.GenerateUUID()
	filepath := "static/upload/image/" + uid + ".png"
	if err := c.SaveUploadedFile(image_file, filepath); err != nil {
		c.JSON(201, gin.H{"msg": err, "img_path": nil})
	}else{
		image_url := "/"+ filepath
		c.JSON(http.StatusOK, gin.H{"msg": nil, "name": uid, "url": image_url})
	}
	return
}

func DeleteFile(c *gin.Context) {
	file_path, ok := c.GetPostForm("file_path")
	if !ok {
		c.JSON(201, gin.H{"msg": "参数获取失败", "data": nil})
		return
	}
	err := os.Remove(file_path)
	if err != nil {
		c.JSON(202, gin.H{"msg": err})
	}else{
		c.JSON(http.StatusOK, gin.H{"msg": nil})
	}
	return
}